import {defineStore} from "pinia";
import Cookies from "js-cookie";
import {ref} from "vue";

const remember = ref(false)
const cookiesStorage = {
    setItem(key, value) {
        console.log(`setItem: ${key}: ${value}`);
        let myValue = JSON.parse(value);
        console.log(`remember: ${remember.value}`)
        if (remember.value){
            return Cookies.set(key, myValue.token,{expires: 7});
        }else {
            return Cookies.set(key, myValue.token);
        }
    },
    getItem(key) {
        console.log(`getItem: ${key}`);
        return JSON.stringify({
            token: Cookies.get(key),
        })
    }
}
export const useTokenStore = defineStore("token", {
    //存储数据的地方
    state(){
        return{
            token: null
        }
    },
    //put functions in actions
    actions:{
        setToken(newToken,rem){//add token
            console.log("setToken called");
            this.token = newToken;
            remember.value = rem
        },
        removeToken(){
            console.log("removeToken");
            this.token = null;
        }
    },
    persist:{
        storage: cookiesStorage
        //enabled:true //Enable caching, which will be stored in local storage by default.
    }
})